﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using ERP.Common.Results;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 生产系统-班组设置
    /// </summary>
    public class TeamSetServices : ApplicationService, ITeamSetServices
    {
        private readonly IRepository<TeamSet, int> _teamsetrepository;
        private readonly ILogger<TeamSetServices> _logger;

        public TeamSetServices(
            IRepository<TeamSet, int> teamsetrepository,
            ILogger<TeamSetServices> logger)
        {
            _teamsetrepository = teamsetrepository;
            _logger = logger;
        }

        /// <summary>
        /// 添加班组设置
        /// </summary>
        /// <param name="teamSetDto"></param>
        /// <returns></returns>
        public async Task<int> AddTeams(TeamSetDto teamSetDto)
        {
            var addtteam = ObjectMapper.Map<TeamSetDto, TeamSet>(teamSetDto);
            var i = await _teamsetrepository.InsertAsync(addtteam);
            return i == null ? 0 : i.Id;
        }

        /// <summary>
        /// 显示班组设置
        /// </summary>
        /// <returns></returns>
        public async Task<List<TeamSet>> GetTeamSet()
        {
            var teamlist = await _teamsetrepository.GetListAsync();
            return teamlist;
        }

        /// <summary>
        /// 获取单个班组数据
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        public async Task<TeamSet> GetTeamById(int id)
        {
            try
            {
                var team = await _teamsetrepository.FindAsync(id);
                return team;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取班组数据失败");
                throw;
            }
        }

        /// <summary>
        /// 更新班组设置
        /// </summary>
        /// <param name="team">更新数据</param>
        /// <returns></returns>
        public async Task<bool> UpdateTeam(TeamSet team)
        {
            try
            {
                _logger.LogInformation($"UpdateTeam被调用，team.Id: {team?.Id}");
                
                if (team == null || team.Id <= 0)
                {
                    _logger.LogWarning($"UpdateTeam参数无效: team is null={team == null}, Id={team?.Id}");
                    return false;
                }

                var existingTeam = await _teamsetrepository.GetAsync(team.Id);
                if (existingTeam == null)
                {
                    _logger.LogWarning($"UpdateTeam未找到ID为{team.Id}的班组");
                    return false;
                }

                _logger.LogInformation($"UpdateTeam更新前: ID={existingTeam.Id}, Number={existingTeam.TeamNumber}, Name={existingTeam.TeamName}, Type={existingTeam.TeamType}");
                
                existingTeam.TeamNumber = team.TeamNumber;
                existingTeam.TeamName = team.TeamName;
                existingTeam.TeamType = team.TeamType;

                _logger.LogInformation($"UpdateTeam更新后: ID={existingTeam.Id}, Number={existingTeam.TeamNumber}, Name={existingTeam.TeamName}, Type={existingTeam.TeamType}");

                await _teamsetrepository.UpdateAsync(existingTeam);
                _logger.LogInformation($"UpdateTeam成功更新班组ID={existingTeam.Id}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新班组时发生错误");
                return false;
            }
        }

        public async Task<APIResult<bool>> UpdateTeamSetAsync(TeamSetUpdateDto input)
        {
            try
            {
                if (input == null || input.Id <= 0)
                {
                    return APIResult<bool>.CreateError("无效的输入数据");
                }

                var existingTeam = await _teamsetrepository.GetAsync(input.Id);
                if (existingTeam == null)
                {
                    return APIResult<bool>.CreateError("班组不存在");
                }

                // 更新属性
                existingTeam.TeamNumber = input.TeamNumber;
                existingTeam.TeamName = input.TeamName;
                existingTeam.TeamType = input.TeamType;

                await _teamsetrepository.UpdateAsync(existingTeam);
                
                return APIResult<bool>.CreateSuccess(true, "更新成功");
            }
            catch (Exception ex)
            {
                return APIResult<bool>.CreateError($"更新失败：{ex.Message}");
            }
        }

        public async Task<APIResult<bool>> DeleteTeamSetAsync(int id)
        {
            try
            {
                // 检查班组是否存在
                var teamSet = await _teamsetrepository.GetAsync(id);
                if (teamSet == null)
                {
                    return APIResult<bool>.CreateError("班组不存在");
                }

                // 删除班组
                await _teamsetrepository.DeleteAsync(id);
                
                return APIResult<bool>.CreateSuccess(true, "删除成功");
            }
            catch (Exception ex)
            {
                return APIResult<bool>.CreateError($"删除失败：{ex.Message}");
            }
        }
    }
}
